import MarkdownIt from 'markdown-it'

import glob from 'fast-glob'
import { resolve, basename } from 'path'
export const docRoot = resolve(__dirname, '..')

const combineMarkdown = (code, headers) => {
  const frontmatterEnds = code.indexOf('---\n\n')
  const firstHeader = code.search(/\n#{1,6}\s.+/)
  const sliceIndex =
    firstHeader < 0
      ? frontmatterEnds < 0
        ? 0
        : frontmatterEnds + 4
      : firstHeader

  if (headers.length > 0)
    code =
      code.slice(0, sliceIndex) + headers.join('\n') + code.slice(sliceIndex)

  return `${code}\n`
}
let compPaths = []
// 自定义vite插件
export function MarkdownTransform() {
  return {
    name: 'vite-plugin-md-transform',
    enforce: 'pre',
    async buildStart() {
      compPaths = await glob(['zh-CN'], {
        cwd: docRoot,
        absolute: true,
        onlyDirectories: true,
      })
    },
    async transform(code, id) {
      if (!id.endsWith('.md')) return
      const componentId = basename(id, '.md')
      if (id.indexOf('zh-CN') < 0) return
      const combineScriptSetup = `\n<script setup>
            const demos = import.meta.globEager('../demo/${componentId}/*.vue')
            </script>
        `
      return combineMarkdown(code, [combineScriptSetup])
    },
  }
}
